package com.bt7274.controller;

import com.bt7274.config.MinIOConfig;
import com.bt7274.base.MinIOUtil;
import com.bt7274.grace.result.GraceJSONResult;
import com.bt7274.grace.result.ResponseStatusEnum;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @Data 2025/5/27 15:48
 * @Author hp
 * @Version 1.0
 * @Description FileController
 */
@RestController
@RequestMapping("file")
public class FileController {
    @Resource
    private MinIOConfig minIOConfig;

    @PostMapping("uploadImage")
    public GraceJSONResult uploadImage(@RequestParam("file") MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        if(StringUtils.isBlank(filename)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }
        filename = "image/" + dealWithoutFilename(filename);
        String imageUrl = MinIOUtil.uploadFile(minIOConfig.getBucketName(),filename, file.getInputStream(), true);
        GraceJSONResult graceJSONResult = GraceJSONResult.ok("图片上传成功");
        graceJSONResult.setData(imageUrl);
        return graceJSONResult;
    }

    private String dealWithFilename(String filename){
        String suffixName = filename.substring(filename.lastIndexOf("."));
        String fName =filename.substring(0,filename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        return fName +"-"+uuid +suffixName;
    }

    private String dealWithoutFilename(String filename){
        String suffixName=filename.substring(filename.lastIndexOf("."));
        String uuid=UUID.randomUUID().toString();
        return uuid + suffixName;
    }
}
